# 作者：陈睿-cruise
# 2025年02月19日13时16分35秒
# 2979386061@qq.com
import multiprocessing
import os

# 定义全局变量
global_var = 0


def worker():
    global global_var
    print(f"Worker (PID: {os.getpid()}) is starting, global_var={global_var}")
    # 修改全局变量
    global_var += 1
    print(f"Worker (PID: {os.getpid()}) finished, global_var={global_var}")


if __name__ == "__main__":
    print(f"Main process (PID: {os.getpid()}) is starting, global_var={global_var}")

    # 创建两个子进程
    process1 = multiprocessing.Process(target=worker)
    process2 = multiprocessing.Process(target=worker)

    # 启动进程
    process1.start()
    process2.start()

    # 等待进程结束
    process1.join()
    process2.join()

    print(f"Main process (PID: {os.getpid()}) finished, global_var={global_var}")












import multiprocessing
import os


def worker(shared_var):
    print(f"Worker (PID: {os.getpid()}) is starting, shared_var={shared_var.value}")
    # 修改共享变量
    shared_var.value += 1
    print(f"Worker (PID: {os.getpid()}) finished, shared_var={shared_var.value}")


if __name__ == "__main__":
    # 使用 Value 创建共享变量
    shared_var = multiprocessing.Value('i', 0)  # 'i' 是表示整数类型

    print(f"Main process (PID: {os.getpid()}) is starting, shared_var={shared_var.value}")

    # 创建两个子进程
    process1 = multiprocessing.Process(target=worker, args=(shared_var,))
    process2 = multiprocessing.Process(target=worker, args=(shared_var,))

    # 启动进程
    process1.start()
    process2.start()

    # 等待进程结束
    process1.join()
    process2.join()

    print(f"Main process (PID: {os.getpid()}) finished, shared_var={shared_var.value}")
